import subprocess
import sys

def install_packages(packages: list, mode: str):
    shell = ['true']
    if mode == 'pacman':
        shell = ['sudo', 'pacman', '-S', '--noconfirm'] + packages
    elif mode == 'yay':
        shell = ['yay', '-S', '--noconfirm'] + packages
    elif mode == 'apt':
        shell = ['sudo', 'apt-get', 'install', '-y'] + packages
    elif mode == 'pip':
        shell = ['pip', 'install', '-U', '--break-system-packages'] + packages
    with subprocess.Popen(shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
        result = b''
        accum = b''
        while p.poll() is None:
            try:
                stdout, stderr = p.communicate(b'y\n', timeout=15)
                assert stderr is None
            except subprocess.TimeoutExpired:
                p.kill()
                break
            else:
                accum += stdout
                try:
                    sys.stdout.write(accum.decode())
                    accum = b''
                    sys.stdout.flush()
                except UnicodeDecodeError:
                    pass
                result += stdout
        try:
            result = result.decode()
        except UnicodeDecodeError:
            try:
                result = result.decode('latin1')
            except UnicodeDecodeError:
                result = ''
        try:
            p.wait(timeout=2)
        except subprocess.TimeoutExpired:
            pass
        result = {'command': shell, 'output': result, 'exit_code': p.returncode, 'success': p.returncode == 0}
    return result
